package com.anbinh.doctor.fragment.clinic;

import java.io.File;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.anbinh.doctor.R;
import com.anbinh.doctor.adapter.AutoCompleteAdapter;
import com.anbinh.doctor.model.DataResponse;
import com.anbinh.doctor.model.SuggestNamePatient;
import com.anbinh.doctor.model.SuggestNamePatient.PatientSuggest;
import com.anbinh.doctor.model.UserLogin;
import com.anbinh.doctor.request.controller.ServerController;
import com.anbinh.doctor.service.request.OnRequest;
import com.anbinh.doctor.utils.Utils;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;

public class FragmentClinicSendMessages extends Fragment {
	private static FragmentClinicSendMessages fragment = null;
	private View mView;
	private UserLogin userLogin;
	private ImageLoader imageLoader;
	private EditText edTieude;
	private TextView dinhkem;
	private EditText edNoidung;
	private Button btnTraloi;
	private String mTitle;
	private String mContent;
	private AutoCompleteTextView mEdkeySearch;
	private AutoCompleteAdapter adapter;
	protected PatientSuggest currentPatient;
	private int doctorid;

	public static FragmentClinicSendMessages newInstance() {
		if (fragment == null) {
			fragment = new FragmentClinicSendMessages();
		}
		return fragment;
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		userLogin = Utils.getAccountModel(getActivity(), Utils.KEY_USER);
		imageLoader = ImageLoader.getInstance();
		imageLoader.init(ImageLoaderConfiguration.createDefault(getActivity()
				.getApplicationContext()));
	}

	@Override
	public void onResume() {
		super.onResume();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mView = inflater.inflate(R.layout.fragment_send_message, null);
		doctorid=FragmentDoctorList.newInstance().getCurrentDoctors().getId();
		return mView;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		edTieude = (EditText) mView.findViewById(R.id.edTieude);
		dinhkem = (TextView) mView.findViewById(R.id.dinhkem);
		edNoidung = (EditText) mView.findViewById(R.id.edNoidung);
		btnTraloi = (Button) mView.findViewById(R.id.btnTraloi);
		btnTraloi.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				mTitle = edTieude.getText().toString().trim();

				if (mTitle.isEmpty()) {
					Utils.showMessage(
							getActivity(),
							getActivity().getResources().getString(
									R.string.vui_long_nhap_tieu_de));
					return;
				}
				mContent = edNoidung.getText().toString().trim();
				if (mContent.length() == 0) {
					Utils.showMessage(
							getActivity(),
							getActivity().getResources().getString(
									R.string.vui_long_nhap_noi_dung));
					return;
				}
				String fileName = "";
				if (edTieude != null && edTieude.getTag() != null) {
					fileName = edTieude.getTag().toString();
				}
				File file = null;
				if (!TextUtils.isEmpty(fileName)) {
					file = new File(fileName);
				}
				onReplyMessage(file);
			}
		});

		mEdkeySearch = (AutoCompleteTextView) mView
				.findViewById(R.id.edKeySearch);
		mEdkeySearch.setThreshold(1);
		
		mEdkeySearch.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View arg1, int pos,
					long id) {
				currentPatient = adapter.getItem(pos);
				mEdkeySearch.setText(currentPatient.getSent_by_name());
			}

		});
		mEdkeySearch.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(final CharSequence s, int start,
					int before, int count) {
				if (s.length() < 2) {
					return;
				}
				ServerController.getInstance(getActivity())
						.requestSuggestPatients(userLogin.getData().getToken(),
								s.toString(),doctorid,
								new OnRequest<SuggestNamePatient>() {

									@Override
									public void onSuccess(
											SuggestNamePatient data) {
										if (data.getData().getListName().size() == 0) {
											return;
										}
										/*adapter.addAll(data.getData()
												.getListName());
										adapter.notifyDataSetChanged();*/
										
										adapter = new AutoCompleteAdapter(getActivity(),
												R.layout.item_autocomplete, data.getData()
												.getListName());
										mEdkeySearch.setAdapter(adapter);
										
									}

									@Override
									public void onError(int errorCode,
											String message) {
										// TODO Auto-generated method stub
									}
								});

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
			}
		});
	}

	public void setIntentFile(Intent intent) {
		dinhkem.setVisibility(View.VISIBLE);
		if (intent == null) {
			return;
		}
		Uri uri = intent.getData();
		if (uri == null) {
			return;
		}
		String file = Utils.getRealPathFromURI(getActivity(), uri);
		String data[];
		if (!TextUtils.isEmpty(file)) {
			data = file.split("/");
			if (data != null && data.length > 0) {
				dinhkem.setText(data[data.length - 1]);
			}
		}
		Log.d("UTILS", "URI: " + uri + "\n" + file);
		dinhkem.setTag(file);
	}

	public void onReplyMessage(File file) {
		Utils.onLoadding(mView, true);
		int sent_by_user_id = currentPatient.getSent_by_user_id();
		ServerController.getInstance(getActivity())
				.requestNotificationSendMessage(userLogin.getData().getToken(),
						sent_by_user_id, mTitle, mContent, file,doctorid,
						new OnRequest<DataResponse>() {

							@Override
							public void onSuccess(DataResponse data) {
								Utils.onLoadding(mView, false);
								if (getActivity() == null)
									return;
								Utils.showMessage(getActivity(),
										data.getDescription());

							}

							@Override
							public void onError(int errorCode, String message) {
								Utils.onLoadding(mView, false);
							}
						});
	}
}
